package com.yimils.website.desktop.controller;



import com.yimils.website.desktop.entity.Article;
import com.yimils.website.desktop.rsp.ArticleListRsp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/pc")
public class PcController {

    @GetMapping("/content/{id}")
    public String show(@PathVariable Long id, Model model) {
        RestTemplate rt = new RestTemplate();

        ArticleListRsp rsp = null;
        if (id >= 100 && id < 200) {
            rsp = rt.getForEntity("http://www.yimils.com/mock/list_up.json", ArticleListRsp.class).getBody();
        } else {
            rsp = rt.getForEntity("http://www.yimils.com/mock/list_down.json", ArticleListRsp.class).getBody();
        }
        for (Article article : rsp.getRsp().getDataList()) {
            if (id.equals(article.getId())) {
                model.addAttribute("title", article.getTitle());
                break;
            }
        }
        String content = rt.getForObject("http://www.yimils.com/mock/" + id + ".txt", String.class);
        model.addAttribute("content", content);
        return "news_detail";
    }

    @GetMapping("/content")
    public String getNews(Model model) {
        RestTemplate rt = new RestTemplate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        ArticleListRsp up = rt.getForEntity("http://www.yimils.com/mock/list_up.json", ArticleListRsp.class).getBody();
        ArticleListRsp down = rt.getForEntity("http://www.yimils.com/mock/list_down.json", ArticleListRsp.class).getBody();

        for (Article article : up.getRsp().getDataList()) {
            article.setPublic_time(new Date(article.getPublic_time().getTime() * 1000));
            article.setDate(sdf.format(article.getPublic_time()));
        }

        for (Article article : down.getRsp().getDataList()) {
            article.setPublic_time(new Date(article.getPublic_time().getTime() * 1000));
            article.setDate(sdf.format(article.getPublic_time()));
        }

        model.addAttribute("list_up", up.getRsp().getDataList());
        model.addAttribute("list_down", down.getRsp().getDataList());
        return "news";
    }

}
